<?php
/**
 * @Notes:【】
 * @Date: 2022-06-05 21:09
 */

namespace App\Notice;

use App\Dao\Settings\SettingsTaskRefreshDao;
use App\Dao\Settings\SettingsTaskTopDao;
use App\Dao\Task\TaskDao;
use App\Dao\User\UserDao;
use App\Model\Task\TaskPayment;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;

class TaskNotice extends \Yurun\PaySDK\Weixin\Notify\Pay
{
    public function __exec()
    {
        $data = $this->data;
        $task_payment_id = $data['out_trade_no'];
        $this->handel($task_payment_id, $data['total_fee']);
    }

    public function notice()
    {
        $params = new \Yurun\PaySDK\Weixin\Params\PublicParams;
        $pay_config = systemConfig(['wx_app_id', 'wx_mch_id', 'wx_key']);
        $params->appID = $pay_config['wx_app_id'];
        $params->mch_id = $pay_config['wx_mch_id'];
        $params->key = $pay_config['wx_key'];
        $pay = new \Yurun\PaySDK\Weixin\SDK($params);
        $pay->notify(new static());
    }

    public function getNotifyData()
    {
        return \Yurun\PaySDK\Lib\XML::fromString(App(RequestInterface::class)->getBody()->getContents());
    }

    /**
     * @Inject()
     * @var TaskPayment
     */
    protected $taskPayment;


    /**
     * @Inject()
     * @var TaskDao
     */
    protected $taskDao;

    public function handel($task_payment_id, $total_fee)
    {
        Db::beginTransaction();
        try {
            $taskPayment = $this->taskPayment->where('id', $task_payment_id)->first();
            if ($taskPayment->status == 1) {
                _Exception('已经支付了');
            }
            $taskPayment->status = 1;

            $taskPayment->pay_price = bcdiv($total_fee, 100, 2);
            $taskPayment->save();
            switch ($taskPayment->types) {
                case 'refresh':
                    $num = App(SettingsTaskRefreshDao::class)
                        ->where('id', $taskPayment->refresh_id)
                        ->value('num');
                    App(UserDao::class)->where('uid', $taskPayment->user_id)->increment('refresh_num', $num);
                    break;
                case "top":
                    $num = App(SettingsTaskTopDao::class)
                        ->where('id', $taskPayment->top_id)
                        ->value('num');
                    App(UserDao::class)->where('uid', $taskPayment->user_id)->increment('top_num', $num);
                    break;
                default:
                    $task = App(TaskDao::class)->where('id', $taskPayment->task_id)->first();
                    $task->status = 1;
                    $task->pay_status = 1;
                    $task->save();
                    break;
            }
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            _Exception($exception->getMessage());
        }
        return true;
    }
}